package com.hellacutty.shake;

import android.os.AsyncTask;
import android.util.Log;

public class CountdownAsyncTask extends AsyncTask<Void, Integer, Void> {

    private CountdownBeforeStartActivity mActivity;

    public CountdownAsyncTask(CountdownBeforeStartActivity activity) {
        mActivity = activity;
    }

    // Can change activity this task points to.
    // e.g. when activity recreated after orientation change.
    public void setActivity(CountdownBeforeStartActivity activity) {
        mActivity = activity;
    }

    // Runs on main thread.
    @Override
    protected void onPreExecute() {
    }

    // Runs on main thread.
    @Override
    protected void onProgressUpdate(Integer... count) {
        if (mActivity != null) {
            mActivity.updateCounter(count[0]);
        }
    }

    // Runs on main thread.
    @Override
    protected void onPostExecute(Void result) {
    }

    // Runs in separate thread.
    @Override
    protected Void doInBackground(Void... params) {
        for (int i = 3; i >= 0; i--) {
            if (isCancelled()) {
                break;
            }
            Log.i("CountTask", Integer.toString(i));
            try {
                Thread.sleep(1000);
                publishProgress(i);
            } catch (InterruptedException e) {
                Log.e("CountTask", "Sleep interrupted.");
            }
        }

        return null;
    }
}

